package org.smileface.designpattern.builder;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: chujian
 * @since: 2022-02-19 21:41
 **/
@Getter
@Setter
public class HttpClient {

    // 协议
    private String protocol;
    // 请求地址
    private String url;
    // 请求方法
    private String method;
    // 请求体
    private String body;
    // 请求头
    private Map<String, String> headers;
    // 请求参数
    private Map<String, String> params;


    public static class HttpClientBuilder {
        private HttpClient client = new HttpClient();

        public HttpClientBuilder protocol(String protocol) {
            client.setProtocol(protocol);
            return this;
        }

        public HttpClientBuilder url(String url) {
            client.setUrl(url);
            return this;
        }

        public HttpClientBuilder method(String method) {
            client.setMethod(method);
            return this;
        }

        public HttpClientBuilder body(String body) {
            client.setBody(body);
            return this;
        }

        public HttpClientBuilder headers(Map<String, String> headers) {
            client.setHeaders(headers);
            return this;
        }

        public HttpClientBuilder addHeader(String header, String headerValue) {
            if (client.getHeaders() == null) {
                client.setHeaders(new HashMap<>());
            }
            client.getHeaders().put(header, headerValue);
            return this;
        }

        public HttpClientBuilder params(Map<String, String> params) {
            client.setParams(params);
            return this;
        }

        public HttpClient build() {
            if (StrUtil.isEmpty(client.getUrl())) {
                throw new RuntimeException("params url cannot be empty");
            }
            if (StrUtil.isEmpty(client.getMethod())) {
                client.setMethod("get");
            }
            return client;
        }

    }

    @Override
    public String toString() {
        return "HttpClient{" +
                "url='" + url + '\'' +
                ", method='" + method + '\'' +
                ", body='" + body + '\'' +
                ", headers=" + headers +
                ", params=" + params +
                '}';
    }
}
